﻿using MixingStation.LTWebService;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;

//同步数据
namespace MixingStation
{
    public class SynchronizeHelper
    {
        //同步物料
        public static bool SynchronizeMaterial()
        {
            materialWS[] materialArr = null;
            materialWS[] materialRateArr = null;
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    //获取系统所有用户
                    materialArr = client.getPurMaterial(0, "", "", "");

                    materialRateArr = client.getBuckleRate(0);
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (TimeoutException)
            {
                throw;
            }
            catch (Exception ex)
            {
                LogHelper.error("同步物料时获取系统所有物料异常：" + ex.Message);
                return false;
            }
            if (materialArr == null || materialArr.Length == 0)
            {
                LogHelper.error("未查询到系统物料信息");
                return false;
            }
            string delSql = "delete * from Material where IsSystem = true";
            if (!CommonHelper.DoOpreation(delSql))
                return false;
            List<string> sqlList = new List<string>();
            foreach (materialWS material in materialArr)
            {
                decimal buckleRate = 0;
                string buckleReason = "";
                var query = from temp in materialRateArr
                            where temp.id == material.id
                            select temp;
                foreach (var item in query)
                {
                    buckleRate = item.buckleRate;
                    buckleReason = item.buckleReason;
                    break;
                }
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("insert into Material (Code, Name, DefaultBuckleRate, BuckleReason, IsSystem) values('{0}', '{1}', {2}, '{3}', {4});",
                    material.code, material.name, buckleRate, buckleReason, true);
                sqlList.Add(sb.ToString());
            }
            if (!CommonHelper.InsertDataByBatch(sqlList.ToArray()))
                return false;
            return true;
        }

        //同步供应商
        public static bool SynchronizeSupplier()
        {
            supplierWS[] supplierArr = null;
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    //获取系统所有用户
                    supplierArr = client.getSupplier(0, "", "");
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (TimeoutException)
            {
                throw;
            }
            catch (Exception ex)
            {
                LogHelper.error("同步供应商时获取系统所有供应商异常：" + ex.Message);
                return false;
            }
            if (supplierArr == null || supplierArr.Length == 0)
            {
                LogHelper.error("未查询到系统供应商信息");
                return false;
            }
            string delSql = "delete * from Supplier";
            if (!CommonHelper.DoOpreation(delSql))
                return false;
            List<string> sqlList = new List<string>();
            foreach (supplierWS supplier in supplierArr)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("insert into Supplier (Code, Name, IsSystem) values('{0}', '{1}', {2});",
                    supplier.code, supplier.name, true);
                sqlList.Add(sb.ToString());
            }
            if (!CommonHelper.InsertDataByBatch(sqlList.ToArray()))
                return false;
            return true;
        }

        //同步产地
        public static bool SynchronizePlace()
        {
            placeWS[] placeArr = null;
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    //获取系统所有用户
                    placeArr = client.getPlaces(0, "", "");
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (TimeoutException)
            {
                throw;
            }
            catch (Exception ex)
            {
                LogHelper.error("同步产地时获取系统所有产地异常：" + ex.Message);
                return false;
            }
            if (placeArr == null || placeArr.Length == 0)
            {
                LogHelper.error("未查询到系统产地信息");
                return false;
            }
            string delSql = "delete * from Place";
            if (!CommonHelper.DoOpreation(delSql))
                return false;
            List<string> sqlList = new List<string>();
            foreach (placeWS place in placeArr)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("insert into Place (Code, Name, IsSystem) values('{0}', '{1}', {2});",
                    place.code, place.name, true);
                sqlList.Add(sb.ToString());
            }
            if (!CommonHelper.InsertDataByBatch(sqlList.ToArray()))
                return false;
            return true;
        }

        //同步用户
        public static bool SynchronizeUser(userWs loginUser)
        {
            List<SystemUserInfo> allUserList = new List<SystemUserInfo> ();
            try
            {
                allUserList = GetAllUsers(loginUser);
            }
            catch (System.ServiceModel.EndpointNotFoundException)
            {
                throw;
            }
            catch (TimeoutException)
            {
                throw;
            }
            catch (Exception ex)
            {
                LogHelper.error("同步用户时获取系统所有用户异常：" + ex.Message);
                return false;
            }
            if (allUserList == null || allUserList.Count == 0)
            {
                LogHelper.error("未查询到系统用户信息");
                return false;
            }
            //更新本地用户表
            string delSql = "delete * from [User]";
            if (!CommonHelper.DoOpreation(delSql))
                return false;

            List<string> sqlList = new List<string>();
            foreach (SystemUserInfo user in allUserList)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("insert into [User] (Id, UserName, EmployeeName, [Password]) values('{0}', '{1}', '{2}', '{3}');",
                    user.id.ToString(), user.userName, user.employeeName, user.password);
                sqlList.Add(sb.ToString());
            }
            if (!CommonHelper.InsertDataByBatch(sqlList.ToArray()))
                return false;
            return true;
        }

        private static List<SystemUserInfo> GetAllUsers(userWs loginUser)
        {
            List<SystemUserInfo> allUserList = new List<SystemUserInfo>();
            try
            {
                string strErrMsg = string.Empty;
                int res = ServerCommonHelper.getJsonData("allUser", "", ref strErrMsg);
                if (res != -1)//系统异常或者业务数据异常
                {
                    LogHelper.error(strErrMsg);
                    if (res == 2)
                    {
                        if (!ServerCommonHelper.JsonLogin(loginUser.userame, loginUser.password))
                            return null;
                        SynchronizeUser(loginUser);
                    }
                }
                else//json取值正常
                {
                    string jsondata = CGlobal.strSwapJsonData;
                    CGlobal.strSwapJsonData = string.Empty;
                    if (jsondata == "[]")
                        return null;
                    JArray jar = JArray.Parse(jsondata);
                    for (int i = 0; i < jar.Count; i++)
                    {
                        SystemUserInfo systemUserInfo = new SystemUserInfo();
                        systemUserInfo.id = long.Parse(jar[i]["id"].ToString());
                        systemUserInfo.userName = jar[i]["userName"].ToString();
                        systemUserInfo.employeeName = jar[i]["employeeName"].ToString();
                        systemUserInfo.password = jar[i]["password"].ToString();
                        allUserList.Add(systemUserInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("获取所有用户异常：" + ex.ToString());
                return null;
            }
            return allUserList;
        }
    }
}
